package com.xd.clap.interceptor;

import com.xd.clap.entity.Admin;
import com.xd.clap.exception.LoginException;
import com.xd.clap.utils.JWTUtil;
import com.xd.clap.utils.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;
import static com.xd.clap.commons.SystemConstant.*;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        // 提前检测是否为白名单ip，如果是就直接放行
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        System.out.println(request.getRequestURI());
        if ("/clap/update/checkUpdate".equals(request.getRequestURI()) || "/clap/error".equals(request.getRequestURI())) {
            System.out.println(1111);
            return true;
        }
        if (com.xd.clap.utils.StringUtils.containsSubstring(IP_WHITE_LIST,ip)){
            return true;
        }

        // 访问路径
        String requestURI = request.getRequestURI();
        // 检查是否请求携带token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            token = request.getHeader("Token");
        }
        // 若携带token则检验一下token
        if (StringUtils.hasText(token)){
            Map<String, Object> map = JWTUtil.checkToken(token);
            String phone = (String) map.get("phone");
            // 再去redis中查询是否有token信息
            Admin admin1 = (Admin) redisUtil.get("app-login:" + phone);
            if (Objects.nonNull(admin1) && com.xd.clap.utils.StringUtils.containsSubstring(APP_API,requestURI)){
                return true;
            }
            Admin admin2 = (Admin) redisUtil.get("admin-login:" + phone);
            if (Objects.nonNull(admin2) && com.xd.clap.utils.StringUtils.containsSubstring(ADMIN_API,requestURI)){
                return true;
            }
        }
        // 若走到这没有token则是抛出一个异常
        throw new LoginException(401,"请先登陆后操作！");
    }
}
